'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
    try {
        let rawBody = event.body;

        if (!rawBody) {
            return { code: 400, content: "Missing request body" };
        }

        let params = new URLSearchParams(rawBody);
        let contentStr = params.get("content");

        if (!contentStr) {
            return { code: 400, content: "Invalid data format: missing content" };
        }

        let messages;
        try {
            messages = JSON.parse(contentStr);
        } catch (e) {
            return { code: 400, content: "Invalid JSON format in content" };
        }

        if (!Array.isArray(messages)) {
            return { code: 400, content: "Invalid data format: content is not an array" };
        }

        if (messages.length === 0) {
            return { code: 200, content: "Empty message list, no data to store" };
        }

        // 异步构造记录，加入 appointId 判断逻辑
        let records = await Promise.all(messages.map(async msg => {
            let appointId = null;

            if (msg.senderId && msg.receiverId) {
                const appointRes = await db.collection('appoint_schedule')
                    .where({
                        $or: [
                            { uid: msg.senderId, consultant: msg.receiverId },
                            { uid: msg.receiverId, consultant: msg.senderId }
                        ]
                    })
                    .limit(1)
                    .get();

                if (appointRes.data && appointRes.data.length > 0) {
                    appointId = appointRes.data[0]._id;
                }
            }

            return {
                messageId: msg.messageId,
                type: msg.type,
                senderId: msg.senderId,
                receiverId: msg.receiverId || null,
                groupId: msg.groupId || null,
                senderData: msg.senderData ? JSON.parse(msg.senderData) : null,
                timestamp: msg.timestamp,
                payload: msg.payload,
                appointId: appointId
            };
        }));

        await db.collection('goeasy_messages').add(records);

        return { code: 200, content: "success" };
    } catch (error) {
        console.error("Webhook 接口错误:", error);
        return { code: 500, content: "Internal Server Error" };
    }
};
